package com.enlorenz.core.channel.common.msgutil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 消息解析
 * @author MAC
 */
public class MsgParser {
	public static final String DEFALUT_DATE_FORMAT="yyyyMMddHHmmss";
	//解析完的数据
	private Map<String,String> data=new LinkedHashMap<String,String>();
	//传入的缓存
	private byte [] buff;
	//解析到的位置标记
	private int index=0;
	//字符编码
	private String code="utf-8";

	public MsgParser(byte [] buff){
		this.buff=buff;
	}
	
	public MsgParser(byte [] buff,String code){
		this.buff=buff;
		this.code=code;
	}
	
	/**
	 * 分解定长域
	 * @param key
	 * @param len
	 */
	public void analyzeFixedField(String key,int len){
		try {
			String value = new String(buff,index,len,code).trim();
			index=index+len;
			data.put(key, value);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 分解变长域
	 * @param key
	 * @param lengthFiledLen
	 */
	public void analyzeVarField(String key,int lengthFiledLen){
		try {
			String filedLen = new String(buff,index, lengthFiledLen,code).trim();
			index=index+lengthFiledLen;
			int flInt=Integer.valueOf(filedLen);
			String val=new String(buff,index,flInt,code).trim();
			index=index+flInt;
			data.put(key, val);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public String toString(){
		return data.toString();
	}
	
	public String get(String key){
		return data.get(key);
	}
	
	public Date getDate(String key,String format){
		String data=get(key);
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		try {
			return sdf.parse(data);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Date getDate(String key){
		return getDate(key,DEFALUT_DATE_FORMAT);
	}
}
